<template>
  <div class="repair-container">
    <!-- 报修表单 -->
    <h2>在线报修</h2>
    <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
      <el-form-item label="报修类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择报修类型">
          <el-option label="水电维修" value="water_electric" />
          <el-option label="家电维修" value="appliance" />
          <el-option label="公共设施" value="public" />
          <el-option label="门窗维修" value="doors_windows" />
          <el-option label="空调维修" value="ac" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>

      <el-form-item label="问题描述" prop="description">
        <el-input type="textarea" :rows="4" placeholder="请详细描述需要维修的问题（必填）" v-model="form.description" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交报修</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 历史记录 -->
    <div class="history-section">
      <h3>历史报修记录</h3>
      <el-table :data="repairHistory" v-loading="loading" style="width: 100%" empty-text="暂无报修记录">
        <el-table-column prop="request_id" label="工单号" width="100" />
        <el-table-column prop="type" label="报修类型" width="120">
          <template #default="{ row }">
            {{ repairTypes[row.type] || row.type }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="问题描述" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ repairStatus[row.status] || row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="解决时间" width="160">
          <template #default="{ row }">
            {{ row.resolved_at ? formatTime(row.resolved_at) : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="showDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="报修详情" width="600px">
      <div class="repair-detail" v-if="currentRepair">
        <div class="detail-item">
          <span class="label">工单号：</span>
          <span>{{ currentRepair.request_id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">报修类型：</span>
          <span>{{ repairTypes[currentRepair.type] || currentRepair.type }}</span>
        </div>
        <div class="detail-item">
          <span class="label">问题描述：</span>
          <span>{{ currentRepair.description }}</span>
        </div>
        <div class="detail-item">
          <span class="label">联系电话：</span>
          <span>{{ currentRepair.phone }}</span>
        </div>
        <div class="detail-item">
          <span class="label">当前状态：</span>
          <el-tag :type="getStatusType(currentRepair.status)">
            {{ repairStatus[currentRepair.status] || currentRepair.status }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span>{{ formatTime(currentRepair.created_at) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">解决时间：</span>
          <span>{{ currentRepair.resolved_at ? formatTime(currentRepair.resolved_at) : '--' }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { submitRepairRequest, getUserRepairRequests } from '@/api/api'

const formRef = ref(null)
const loading = ref(false)
const repairHistory = ref([])
const detailVisible = ref(false)
const currentRepair = ref(null)

// 表单数据
const form = reactive({
  type: '',
  description: '',
  phone: ''
})

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择报修类型', trigger: 'change' }],
  description: [{ required: true, message: '请填写问题描述', trigger: 'blur' }],
  phone: [
    { required: true, message: '请填写联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 报修类型
const repairTypes = {
  water_electric: '水电维修',
  appliance: '家电维修',
  public: '公共设施',
  doors_windows: '门窗维修',
  ac: '空调维修',
  other: '其他'
}

// 维修状态映射
const repairStatus = {
  pending: '待处理',
  processing: '处理中',
  completed: '已完成',
  cancelled: '已取消',
  'veniam in': '处理中' // 处理可能的特殊状态
}

// 状态标签类型
const getStatusType = (status) => {
  const statusTagType = {
    pending: 'warning',
    processing: 'primary',
    scheduled: 'info',
    completed: 'success',
    cancelled: 'danger',
    'veniam in': 'primary'
  }
  return statusTagType[status] || ''
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const userId = JSON.parse(localStorage.getItem('userInfo'))?.userId;
        if (!userId) {
          ElMessage.error('请先登录');
          return;
        }
        const requestData = {
          userId,
          description: {
            type: form.type,
            description: form.description,
            phone: form.phone
          }
        }
        const res = await submitRepairRequest(requestData)
        if (res.code === 200) {
          ElMessage.success('报修申请已提交')
          resetForm()
          fetchRepairHistory()
        }
      } catch (error) {
        console.error('提交报修失败:', error)
        ElMessage.error('提交报修失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取历史记录
const fetchRepairHistory = async () => {
  loading.value = true
  try {
    const res = await getUserRepairRequests()
    if (res.code === 200 && res.data) {
      repairHistory.value = res.data.map(item => ({
        request_id: item.requestId,
        type: item.type || 'other',
        description: item.description,
        phone: item.phone || '未知',
        status: item.status,
        created_at: item.createdAt,
        resolved_at: item.resolvedAt,
        assigned_to: item.assignedTo,
        updated_at: item.updatedAt
      }))
    }
  } catch (error) {
    console.error('获取报修记录失败:', error)
    ElMessage.error('获取报修记录失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const showDetail = (repair) => {
  currentRepair.value = repair
  detailVisible.value = true
}

// 初始化
onMounted(() => {
  fetchRepairHistory()
})
</script>

<style scoped>
.repair-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.history-section {
  margin-top: 40px;
}

.repair-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  line-height: 1.5;
}

.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}
</style>